package cn.dgut.training.controller;


import cn.dgut.training.entity.Region;
import cn.dgut.training.service.impl.RegionServiceImpl;
import cn.dgut.training.vo.CommonResponse;
import cn.dgut.training.vo.pageVO.PageVO;
import cn.dgut.training.vo.regionVO.RegionVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/region")
public class RegionController {

    @Resource
    private RegionServiceImpl regionService;

    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public CommonResponse addRegion(@RequestBody Region region){
        return CommonResponse.success(regionService.save(region));
    }

    /*
    *根据pid查找地级市与县级市的查找
    * @Param id 省的id
     */

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public CommonResponse listRegionByPage(){

        List<RegionVO> regionVoList = new ArrayList<>();

        List<Region> provinceList = regionService.listRegion(0);
        for (Region province : provinceList) {

            RegionVO provinceVO = new RegionVO();

            provinceVO.setValue(province.getId(),province.getName(),province.getCode(),province.getRegionType());


            List<Region> cityList = regionService.listRegion( province.getId().intValue());
            List<RegionVO> cityVOList = new ArrayList<>();
            for (Region city : cityList) {
                RegionVO cityVO = new RegionVO();
                cityVO.setValue(city.getId(),city.getName(),city.getCode(),city.getRegionType());

                List<Region> areaList = regionService.listRegion(city.getId().intValue());
                List<RegionVO> areaVOList = new ArrayList<>();
                for (Region area : areaList) {
                    RegionVO areaVO = new RegionVO();
                    areaVO.setValue(area.getId(),area.getName(),area.getCode(),area.getRegionType());
                    areaVOList.add(areaVO);
                }

                cityVO.setChildren(areaVOList);
                cityVOList.add(cityVO);
            }
            provinceVO.setChildren(cityVOList);
            regionVoList.add(provinceVO);
        }

        PageVO pageVO=new PageVO( "region",regionVoList);
//        PageVO pageVO=new PageVO( "region",regionService.listRegion(3));

        return  CommonResponse.success(pageVO);
    }

}
